package com.edu.examhelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.PublicKey;

import net.youmi.android.AdManager;
import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import net.youmi.android.offers.OffersManager;
import net.youmi.android.offers.PointsChangeNotify;

import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Color;
import android.view.MotionEvent;

import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.analytics.MobclickAgent;

public class ExamHelper extends Activity {
	/** Called when the activity is first created. */
	public static final int OPTION_ORDER = 1;//顺序练习
	public static final int OPTION_RDM = 2;//随机练习
	public static final int OPTION_TEST = 3;//模拟考试
	public static final int OPTION_WRONGEXERCISE = 4;//错题库
	public static final int MODE = MODE_PRIVATE;
	public static final String PREFERENCE_NAME = "SaveSetting";//保存设置
	public static final String CONFIG_COURSEID = "0";//课程号,c0,vb1,vfp2;
	public static final String CONFIG_AUTOCHECK = "config_autocheck";//自动确认
	public static final String CONFIG_AUTO2NEXT = "config_auto2next";//答对后自动跳转下一题
	public static final String CONFIG_AUTO2ADDWRONGSET = "config_auto2addwrongset";//自动加入错题库
	
//	private TextView tv = null;
	LinearLayout btn_order;
	LinearLayout btn_rdm;
	LinearLayout btn_test;
	LinearLayout btn_myWAset;
	LinearLayout btn_option;
	LinearLayout btn_score;
	
	private Button btn_onlineanswer = null;
	private Button btn_about = null;
	private ProgressDialog mProgressDialog = null;
	private int TEST_BELONG;
	private int mTotalCount = 0;//试题总数
	//友盟信息反馈
	FeedbackAgent mAgent;
	Dialog dialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//友盟自动更新功能
		UmengUpdateAgent.update(this);
		
		setContentView(R.layout.menu);
		btn_order = (LinearLayout) findViewById(R.id.btn_order);
		btn_rdm = (LinearLayout) findViewById(R.id.btn_rdm);
		btn_test = (LinearLayout) findViewById(R.id.btn_test);
		btn_myWAset = (LinearLayout) findViewById(R.id.btn_myWAset);
		btn_score = (LinearLayout) findViewById(R.id.btn_score);
		btn_option = (LinearLayout) findViewById(R.id.btn_option);
		btn_about = (Button) findViewById(R.id.btn_about);
		btn_onlineanswer = (Button) findViewById(R.id.btn_onlineanswer);
		
		btn_order.setOnTouchListener(otl);
		btn_rdm.setOnTouchListener(otl2);
		btn_myWAset.setOnTouchListener(otl4);
		btn_option.setOnTouchListener(otl5);
		
		//以下为有米广告
	   // 初始化应用的发布ID和密钥，以及设置测试模式
       AdManager.getInstance(this).init("6c528c718917d495","7d1a4a8f2d3db598", false); 
       // 请务必调用以下代码，告诉SDK应用启动，可以让SDK进行一些初始化操作。该接口务必在SDK的初始化接口之后调用。
       OffersManager.getInstance(this).onAppLaunch(); 
       //有米广告结束
		
		// !!!!!!!!sharedPreferencesInit();//!!!!!!!!!!!!!!!!!!初始配置
		SharedPreferences sharedPreferences = getSharedPreferences(
				PREFERENCE_NAME, MODE);
		judgeTheFirstTime2Run();
		
		
		//友盟反馈
		mAgent = new FeedbackAgent(this);
		mAgent.sync();
		
		btn_order.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				final String[] items = getResources().getStringArray(R.array.itemc);
				new AlertDialog.Builder(ExamHelper.this)
				.setTitle("请选择章节")
				.setItems(items, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						TEST_BELONG = which;
						//选择章节
						Intent intent = new Intent();
						intent.putExtra("option", OPTION_ORDER);
						intent.putExtra("belong", TEST_BELONG);
						intent.setClass(ExamHelper.this, ExerciseActivity.class);
						startActivity(intent);
					}
				}).create().show();
				
			}
		});

		btn_rdm.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.putExtra("option", OPTION_RDM);
				intent.setClass(ExamHelper.this, ExerciseActivity.class);
				startActivity(intent);
			}
		});
		/*
		 * 我的错误集
		 */
		btn_myWAset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent().setClass(ExamHelper.this,
						WrongSetShowList.class));
			}
		});
		btn_test.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent().setClass(ExamHelper.this,
						ExamActivity.class));
			}
		});
		/*
		 * 成绩统计
		 */
		btn_score.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//实现分数的曲线显示
				startActivity(new Intent().setClass(ExamHelper.this,
						ShowScoreChart.class));		
			}
		});
		/*
		 * 设置
		 */
		btn_option.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent().setClass(ExamHelper.this,
						OptionActivity.class));				
			}
		});
		btn_onlineanswer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//友盟在线提问
				mAgent.startFeedbackActivity();
			}
		});

		btn_about.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				aboutdialog();
				
			}
		});
		
	}
	
	public OnTouchListener otl = new OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				btn_order.setBackgroundColor(Color.rgb(127, 127, 127));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				btn_order.setBackgroundColor(Color.TRANSPARENT);
			}
			return false;
		}
	};

	public OnTouchListener otl2 = new OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				btn_rdm.setBackgroundColor(Color.rgb(127, 127, 127));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				btn_rdm.setBackgroundColor(Color.TRANSPARENT);
			}
			return false;
		}
	};

	public OnTouchListener otl3 = new OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				btn_test.setBackgroundColor(Color.rgb(127, 127, 127));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				btn_test.setBackgroundColor(Color.TRANSPARENT);
			}
			return false;
		}
	};

	public OnTouchListener otl4 = new OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				btn_myWAset.setBackgroundColor(Color.rgb(127, 127, 127));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				btn_myWAset.setBackgroundColor(Color.TRANSPARENT);
			}
			return false;
		}
	};

	public OnTouchListener otl5 = new OnTouchListener() {

		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				btn_option.setBackgroundColor(Color.rgb(127, 127, 127));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				btn_option.setBackgroundColor(Color.TRANSPARENT);
			}
			return false;
		}
	};

    /** 
     * 用Handler来更新UI 
     */  
    private Handler handler = new Handler(){  
  
        @Override  
        public void handleMessage(Message msg) {      	
            //关闭ProgressDialog  
            mProgressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "试题加载完成", Toast.LENGTH_SHORT).show();
        }};  
	
	private void judgeTheFirstTime2Run() {
		// TODO Auto-generated method stub
		DBAdapter dbAdapter;
		Cursor cursor;
		try {
			dbAdapter = new DBAdapter(this);
			dbAdapter.open();
			cursor = dbAdapter.getAllData();
			
			if (cursor.getCount() == 0) {		
				mProgressDialog = new ProgressDialog(this);
				//设置进度条风格，风格为长形，有刻度的
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				//设置ProgressDialog 标题
				mProgressDialog.setTitle("二级考试");
				//设置ProgressDialog 提示信息
				mProgressDialog.setMessage("试题加载中……");
				//设置ProgressDialog 是否可以按退回按键取消
				mProgressDialog.setCancelable(false);			
				mProgressDialog.show();
				new Thread(){
					@Override 
					public void run() {
						mTotalCount = GetTestCount();
						DataTrans();
						handler.sendEmptyMessage(0); 
					}
				}.start();
			}
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(this, "加载失败，请重新运行程序！", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			exitdialog();
		}
		return false;
	}
	@Override  
    protected void onDestroy() {  
        super.onDestroy();   
		OffersManager.getInstance(this).onAppExit();
    }  
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);//友盟统计分析
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);//友盟统计分析
	}
	

	protected void exitdialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确认退出吗？");

		builder.setTitle("提示");

		builder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface v, int which) {
						// TODO Auto-generated method stub
						finish();
						
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	protected void aboutdialog() {
		
		String copyright;
		AlertDialog.Builder builder = new Builder(this);
		copyright = "全国计算机等级考试考试助手，包括考试，练习，错题库，在线提问等功能\n邮箱：ncrehelper@sina.com\nCopyright©2013 Wisdom Education\nAll Rights Reserved 慧育科技";
		builder.setMessage(copyright);

		builder.setTitle("关于");

		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		builder.create().show();
	}
	//得到试题总数
	public int GetTestCount(){
		int TotalCount = 0;//试题总数
		String tmp;
		InputStream in = getResources().openRawResource(R.raw.testsubject);
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in, "gb2312"));// 注意编码
			
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			Log.e("debug", e1.toString());

		}
		try {
			while ((tmp = br.readLine()) != null) {
				TotalCount++;
			}	
			br.close();
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("debug", e.toString());
		}
		return TotalCount;
		
	}
	/*
	 * 数据转入
	 */
	public void DataTrans() {
		int count = 0;//试题数	
		String tmp, body;
		InputStream in = getResources().openRawResource(R.raw.testsubject);
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in, "gb2312"));// 注意编码
			
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			Log.e("debug", e1.toString());

		}
		String TESTSUBJECT;
		String TESTANSWER;
		String ANSWERA;
		String ANSWERB;
		String ANSWERC;
		String ANSWERD;
		String IMAGENAME;
		String ANALYZE;//答案解析

		int TESTTPYE;//题目类型（判断题2、选择题1）
		int TESTBELONG;//章节
		int COURSEID;//课程号
		int POINTSID;//知识点号
		int DIFFICULT;//难易度
		int EXPR1;

		String[] strings = new String[15];
		ContentValues values = new ContentValues();

		try {
			DBAdapter dbAdapter = new DBAdapter(this);
			dbAdapter.open();
			while ((tmp = br.readLine()) != null) {
				strings = tmp.split("`");
				TESTSUBJECT = strings[1].replace("@", "\n");
				TESTANSWER = strings[2];
				COURSEID = Integer.parseInt(strings[3]);
				TESTTPYE = Integer.parseInt(strings[4]);// Dint
				TESTBELONG = Integer.parseInt(strings[5]);// int
				POINTSID = Integer.parseInt(strings[6]);
				DIFFICULT = Integer.parseInt(strings[7]);
				ANSWERA = strings[8].replace("@", "\n");
				ANSWERB = strings[9].replace("@", "\n");
				ANSWERC = strings[10].replace("@", "\n");
				ANSWERD = strings[11].replace("@", "\n");
				IMAGENAME = "image" + strings[12];
				IMAGENAME.replace("-", "_");
				ANALYZE = strings[13].replace("@", "\n");
				EXPR1 = Integer.parseInt(strings[14]);// integer

				values.clear();
				values.put(DBAdapter.TESTSUBJECT, TESTSUBJECT);
				values.put(DBAdapter.TESTANSWER, TESTANSWER);
				values.put(DBAdapter.COURSEID, COURSEID);
				values.put(DBAdapter.TESTTPYE, TESTTPYE);
				values.put(DBAdapter.TESTBELONG, TESTBELONG);
				values.put(DBAdapter.POINTSID, POINTSID);
				values.put(DBAdapter.DIFFICULT, DIFFICULT);
				values.put(DBAdapter.ANSWERA, ANSWERA);
				values.put(DBAdapter.ANSWERB, ANSWERB);
				values.put(DBAdapter.ANSWERC, ANSWERC);
				values.put(DBAdapter.ANSWERD, ANSWERD);
				values.put(DBAdapter.IMAGENAME, IMAGENAME);
				values.put(DBAdapter.ANALYZE, ANALYZE);
				values.put(DBAdapter.EXPR1, EXPR1);

				dbAdapter.DBInsert(values);	
				//试题计数
				count ++;
				//设置ProgressDialog 进度条进度
				mProgressDialog.setProgress(count*100/mTotalCount);
				Log.i(tmp, tmp);
			}
			br.close();
			in.close();
			body = "";
			Cursor cursor = dbAdapter.getAllData();
			body += cursor.getCount();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e("debug", e.toString());
		}
	}


}